#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""依赖管理模块

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

自动检测目标环境的包管理器并安装缺失的依赖

作者: 大傻逼
版本: v1.0
功能: 自动适配不同Linux发行版的包管理器
警告: 仅用于授权测试环境"""

import os
import sys

# Python 2/3 兼容性处理
if sys.version_info[0] == 2:
    string_types = basestring
    text_type = unicode
    def iteritems(d):
        return d.iteritems()
    def itervalues(d):
        return d.itervalues()
else:
    string_types = str
    text_type = str
    def iteritems(d):
        return d.items()
    def itervalues(d):
        return d.values()
import subprocess
import json
from core.utils import color_green, color_red, color_yellow, color_blue




class DependencyManager:
    """依赖管理器 - 自动检测和安装依赖"""
    
    def __init__(self):
        self.os_info = {}
        self.package_manager = None
        self.required_packages = {
            'python3': ['python3', 'python3-dev', 'python3-pip'],
            'openssh-client': ['openssh-client', 'openssh-clients'],
            'curl': ['curl'],
            'wget': ['wget'],
            'git': ['git'],
            'gcc': ['gcc', 'build-essential'],
            'make': ['make'],
            'systemd': ['systemd']
        }

    def detect_os_release(self):
        """检测操作系统发行版"""
        color_blue("检测操作系统发行版...")
        
        # 检查 /etc/os-release
        if os.path.exists('/etc/os-release'):
            try:
                with open('/etc/os-release', 'r') as f:
                    for line in f:
                        if '=' in line:
                            key, value = line.strip().split('=', 1)
                            self.os_info[key] = value.strip('"')
                
                color_green("✓ 成功读取 /etc/os-release")
                color_blue("  发行版: {}".format(self.os_info.get('NAME', 'Unknown')))
                color_blue("  版本: {}".format(self.os_info.get('VERSION', 'Unknown')))
                color_blue("  ID: {}".format(self.os_info.get('ID', 'Unknown')))
                return True
                
            except Exception as e:
                color_red("读取 /etc/os-release 失败: {}".format(e))
        
        # 备用检测方法
        fallback_files = [
            ('/etc/debian_version', 'debian'),
            ('/etc/redhat-release', 'redhat'),
            ('/etc/centos-release', 'centos'),
            ('/etc/fedora-release', 'fedora'),
            ('/etc/suse-release', 'suse'),
            ('/etc/alpine-release', 'alpine')
        ]
        
        for file_path, distro_id in fallback_files:
            if os.path.exists(file_path):
                try:
                    with open(file_path, 'r') as f:
                        version = f.read().strip()
                    self.os_info['ID'] = distro_id
                    self.os_info['VERSION'] = version
                    color_yellow("通过 {} 检测到: {}".format(file_path, distro_id))
                    return True
                except:
                    continue
        
        color_red("无法检测操作系统发行版")
        return False
    
    def detect_package_manager(self):
        """检测可用的包管理器"""
        color_blue("检测包管理器...")
        
        # 包管理器优先级列表
        package_managers = [
            ('apt', ['apt', 'apt-get'], ['debian', 'ubuntu', 'kali', 'mint']),
            ('dnf', ['dnf'], ['fedora', 'rhel', 'centos']),
            ('yum', ['yum'], ['centos', 'rhel', 'fedora', 'amazon']),
            ('zypper', ['zypper'], ['suse', 'opensuse']),
            ('apk', ['apk'], ['alpine']),
            ('pacman', ['pacman'], ['arch', 'manjaro']),
            ('emerge', ['emerge'], ['gentoo'])
        ]
        
        os_id = self.os_info.get('ID', '').lower()
        
        # 根据OS ID优先选择
        for pm_name, commands, supported_os in package_managers:
            if os_id in supported_os:
                for cmd in commands:
                    if self._check_command_available(cmd):
                        self.package_manager = {
                            'name': pm_name,
                            'command': cmd,
                            'install_cmd': self._get_install_command(pm_name),
                            'update_cmd': self._get_update_command(pm_name)
                        }
                        color_green("✓ 检测到包管理器: {} ({})".format(pm_name, cmd))
                        return True
        
        # 如果基于OS ID没找到，尝试所有可用的
        for pm_name, commands, _ in package_managers:
            for cmd in commands:
                if self._check_command_available(cmd):
                    self.package_manager = {
                        'name': pm_name,
                        'command': cmd,
                        'install_cmd': self._get_install_command(pm_name),
                        'update_cmd': self._get_update_command(pm_name)
                    }
                    color_yellow("检测到包管理器: {} ({})".format(pm_name, cmd))
                    return True
        
        color_red("未找到支持的包管理器")
        return False
    
    def _check_command_available(self, command):
        """检查命令是否可用"""
        try:
            result = subprocess.run(['which', command], 
                                  capture_output=True, text=True, timeout=5)
            return result.returncode == 0
        except:
            return False
    
    def _get_install_command(self, pm_name):
        """获取安装命令模板"""
        install_commands = {
            'apt': 'apt-get install -y {}',
            'dnf': 'dnf install -y {}',
            'yum': 'yum install -y {}',
            'zypper': 'zypper install -y {}',
            'apk': 'apk add {}',
            'pacman': 'pacman -S --noconfirm {}',
            'emerge': 'emerge {}'
        }
        return install_commands.get(pm_name, 'echo "不支持的包管理器: {}"')
    
    def _get_update_command(self, pm_name):
        """获取更新命令"""
        update_commands = {
            'apt': 'apt-get update',
            'dnf': 'dnf check-update',
            'yum': 'yum check-update',
            'zypper': 'zypper refresh',
            'apk': 'apk update',
            'pacman': 'pacman -Sy',
            'emerge': 'emerge --sync'
        }
        return update_commands.get(pm_name, 'echo "不支持的包管理器更新"')
    
    def check_dependency(self, package_name):
        """检查单个依赖是否已安装"""
        if package_name == 'python3':
            # 特殊处理Python3检查
            try:
                result = subprocess.run(['python3', '--version'], 
                                      capture_output=True, text=True, timeout=5)
                if result.returncode == 0:
                    version = result.stdout.strip()
                    color_green("✓ {} 已安装: {}".format(package_name, version))
                    return True
            except:
                pass
        
        # 通用命令检查
        if self._check_command_available(package_name):
            color_green("✓ {} 已安装".format(package_name))
            return True
        
        # 包管理器特定检查
        if self.package_manager:
            pm_name = self.package_manager['name']
            
            if pm_name == 'apt':
                try:
                    result = subprocess.run(['dpkg', '-l', package_name], 
                                          capture_output=True, text=True, timeout=5)
                    if result.returncode == 0 and 'ii' in result.stdout:
                        color_green("✓ {} 已安装 (dpkg)".format(package_name))
                        return True
                except:
                    pass
            
            elif pm_name in ['dnf', 'yum']:
                try:
                    result = subprocess.run(['rpm', '-q', package_name], 
                                          capture_output=True, text=True, timeout=5)
                    if result.returncode == 0:
                        color_green("✓ {} 已安装 (rpm)".format(package_name))
                        return True
                except:
                    pass
        
        color_red("✗ {} 未安装".format(package_name))
        return False
    
    def install_dependency(self, package_name, auto_confirm=False):
        """安装单个依赖"""
        if not self.package_manager:
            color_red("未检测到包管理器，无法安装依赖")
            return False
        
        # 获取包名候选列表
        package_candidates = self.required_packages.get(package_name, [package_name])
        
        color_blue("尝试安装 {}...".format(package_name))
        
        # 如果不是自动确认，询问用户
        if not auto_confirm:
            color_yellow("是否安装 {}? (y/n): ".format(package_name))
            try:
                response = input().strip().lower()
                if response not in ['y', 'yes', '是']:
                    color_yellow("跳过安装")
                    return False
            except KeyboardInterrupt:
                color_yellow("\n用户取消安装")
                return False
        
        # 更新包列表
        color_blue("更新包列表...")
        try:
            update_cmd = self.package_manager['update_cmd']
            result = subprocess.run(update_cmd.split(), 
                                  capture_output=True, text=True, timeout=30)
            if result.returncode == 0:
                color_green("✓ 包列表更新成功")
            else:
                color_yellow("包列表更新失败，继续安装...")
        except Exception as e:
            color_yellow("包列表更新异常: {}".format(e))
        
        # 尝试安装包
        for package in package_candidates:
            color_blue("尝试安装包: {}".format(package))
            
            install_cmd = self.package_manager['install_cmd'].format(package)
            
            try:
                result = subprocess.run(install_cmd.split(), 
                                      capture_output=True, text=True, timeout=120)
                
                if result.returncode == 0:
                    color_green("✓ {} 安装成功".format(package))
                    
                    # 验证安装
                    if self.check_dependency(package_name):
                        return True
                else:
                    color_red("✗ {} 安装失败".format(package))
                    color_red("错误信息: {}".format(result.stderr))
                    
            except Exception as e:
                color_red("安装 {} 时发生异常: {}".format(package, e))
        
        color_red("所有候选包安装失败: {}".format(package_candidates))
        return False
    
    def check_all_dependencies(self):
        """检查所有必需的依赖"""
        color_blue("=== 依赖检查 ===")
        
        missing_deps = []
        
        for dep_name in self.required_packages.keys():
            if not self.check_dependency(dep_name):
                missing_deps.append(dep_name)
        
        if missing_deps:
            color_yellow("发现 {} 个缺失依赖: {}".format(len(missing_deps), ', '.join(missing_deps)))
            return missing_deps
        else:
            color_green("✓ 所有依赖都已安装")
            return []
    
    def install_missing_dependencies(self, missing_deps=None, auto_confirm=False):
        """安装缺失的依赖"""
        if missing_deps is None:
            missing_deps = self.check_all_dependencies()
        
        if not missing_deps:
            color_green("没有需要安装的依赖")
            return True
        
        color_blue("=== 依赖安装 ===")
        
        success_count = 0
        
        for dep in missing_deps:
            if self.install_dependency(dep, auto_confirm):
                success_count += 1
        
        color_blue("安装结果: {}/{} 成功".format(success_count, len(missing_deps)))
        
        if success_count == len(missing_deps):
            color_green("✓ 所有依赖安装成功")
            return True
        else:
            color_red("✗ {} 个依赖安装失败".format(len(missing_deps) - success_count))
            return False
    
    def get_system_info(self):
        """获取系统信息摘要"""
        info = {
            'os_info': self.os_info,
            'package_manager': self.package_manager,
            'missing_dependencies': self.check_all_dependencies()
        }
        return info
    
    def initialize(self):
        """初始化依赖管理器"""
        color_blue("=== 初始化依赖管理器 ===")
        
        # 检测操作系统
        if not self.detect_os_release():
            color_red("操作系统检测失败")
            return False
        
        # 检测包管理器
        if not self.detect_package_manager():
            color_red("包管理器检测失败")
            return False
        
        color_green("✓ 依赖管理器初始化成功")
        return True

def main():
    """主函数 - 用于测试"""
    dep_manager = DependencyManager()
    
    if not dep_manager.initialize():
        sys.exit(1)
    
    # 检查依赖
    missing_deps = dep_manager.check_all_dependencies()
    
    if missing_deps:
        print("\n发现缺失依赖: {}".format(missing_deps))
        print("是否自动安装? (y/n): ", end='')
        
        try:
            response = input().strip().lower()
            if response in ['y', 'yes', '是']:
                dep_manager.install_missing_dependencies(missing_deps, auto_confirm=False)
        except KeyboardInterrupt:
            print("\n用户取消")
    
    # 显示系统信息
    info = dep_manager.get_system_info()
    print("\n系统信息: {}".format(json.dumps(info, indent=2, ensure_ascii=False)))

if __name__ == "__main__":
    main()